package com.litesuits.sdk.handler;

import android.content.Intent;
import android.os.Process;
import android.util.Log;
import com.litesuits.sdk.LiteApp;
import com.litesuits.sdk.act.BugReportActivity;
import com.litesuits.sdk.config.LiteConfig;

/**
 * Try to catch the uncaught exception. when a thread exits due to an uncaught
 * exception, we log a message and exit.
 *
 * @author MaTianyu on 2015-05-05
 */
public abstract class DefaultUncaughtHandler implements Thread.UncaughtExceptionHandler {
    private static final String TAG = DefaultUncaughtHandler.class.getSimpleName();
    private static volatile boolean mCrashing = false;

    public void uncaughtException(Thread t, Throwable e) {
        try {
            if (mCrashing)
                return;
            mCrashing = true;
            handleException(t, e);
            StringBuilder message = new StringBuilder();
            e.getStackTrace()[0].getClassName();
            message.append("\nFATAL EXCEPTION :")
                   .append("\n_____________________________________")
                   .append("\nThread: ").append(t.getName()).append(" , ")
                   .append("tid: ").append(Process.myTid()).append(" , ")
                   .append("\nProcess pid: ").append(Process.myPid()).append(" , ")
                   .append("uid: ").append(Process.myUid())
                   .append(e.getCause())
                   .append("\n_____________________________________");
            android.util.Log.e(TAG, message.toString(), e);
            if (LiteConfig.bugResportOpen) {
                reportException(t, e);
            }
        } catch (Throwable t2) {
            android.util.Log.e(TAG, "Error: crash reporting", t2);
        } finally {
            Process.killProcess(Process.myPid());
            System.exit(0);
        }
    }

    protected void reportException(Thread t, Throwable e) {
        Intent bugReportIntent = new Intent(LiteApp.getInstance(), BugReportActivity.class);
        bugReportIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        bugReportIntent.putExtra(BugReportActivity.exceptionMsg, Log.getStackTraceString(e));
        LiteApp.getInstance().startActivity(bugReportIntent);
    }

    protected abstract void handleException(Thread t, Throwable e);
}